<template style="padding:0px;">
  <div class="point">
    <panel v-loading="loading" :list="pointList" @search="getList" @add="handleAdd" @edit="handleEdit" @del="handleDel"
      @disable="handleDisable" @enable="handleEnsable"></panel>
    <mapButton v-model="mapType"></mapButton>
    <div class="zoom">
      <div class="zoom-in" @click="zoomIn">+</div>
      <div class="zoom-out" @click="zoomOut">-</div>
    </div>
    <xdh-map v-if="showMap" ref="map" type="Amap" :zoom="zoom" :min-zoom="8" :max-zoom="18" :center="center"
      @pointermove="overLayMouseMove" :layer-config="layerConfig" @ready="readyHandle" @moveend="handleMapChange"
      @on-dragUp="dragUpHandle">
      <!-- 地图覆盖物加弹窗 设备 start-->
      <template v-for="(item,idx) in pointList">
        <xdh-map-html :key="idx" :position="[item.lon,item.lat]" @click="showPopup(item.pointId)" @mousedown="overLayMouseDown"
          @mouseup="overLayMouseUp(item)">
          <div :id="'marker_'+item.pointId" class="marker_point">
            <img :src="markers.point" width="28" height="35">
            <div class="markers-label-1">{{item.pointName}}</div>
          </div>
        </xdh-map-html>
      </template>
      <!-- 地图覆盖物加弹窗 设备 end-->
    </xdh-map>
    <span style="font-size:0;position:absolute">{{lonlat}}</span>
    <Add ref="add" @refresh="getList"></Add>
  </div>
</template>

<script>
  import mapResizeMixins from "@/views/mapResizeMixins";
  import mapButton from "./mapButton";
  import popupPanel from "./popupPanel";
  import panel from "./panel";
  import Add from "./add";
  import Drag from './drag'
  import { listPoint, addPoint, getPoint, updatePoint, changeStatus, delPoint } from "../../../../api/page/device";
  import { Modify } from "ol/interaction.js";

  let timed = null;
  export default {
    name: "Index",
    mixins: [mapResizeMixins],
    components: {
      mapButton,
      panel,
      popupPanel,
      Add
    },
    data() {
      return {
        dragPointId: undefined,
        dragBeforePoint: undefined,
        loading: false,
        lonlat: "",
        center: [108.378179, 22.936135],
        zoom: 18,
        isZooming: false,
        showMap: true, //显示地图
        mapType: 1, //地图的类型： 1.电子地图 2.影像地图
        olMap: null,
        isConfigPoint: false,
        markers: {
          point: require("@/assets/image/markers/point.png")
        },
        // 点位列表
        pointList: [],
        dragOverlay: false,
        htmlPoint: [120.05, 30.05]
      };
    },
    watch: {
      async mapType(val) {
        this.showMap = false;
        await this.$nextTick();
        this.showMap = true;
      }
    },
    computed: {
      layerConfig() {
        // 1.电子地图 2.影像地图
        let servers = {
          "1": "https://webst01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&style=6",
          "2": "http://webrd03.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}&lang=zh_cn"
        };
        return {
          Amap: {
            title: "高德",
            server: servers[this.mapType]
          }
        };
      }
    },
    methods: {
      readyHandle(map, mapComp) {
        this.olMap = map;
        let dragInteraction = new Drag(mapComp, {
          featureDefine: (feature) => { // 自定义参数过滤需要拖动的组件
            let feaProps = feature.getProperties()
            if (feaProps.dragFlag) {
              return feature
            }
          }
        });
        this.olMap.addInteraction(dragInteraction)
      },
      handleChange(t, v) {
        console.log(t, v);
        this[t] = v;
      },
      hidePopup(e) {
        e.popupFlag = false;
      },
      handleDisable(e) {
        var self = this;
        this.$confirm("确定禁用点位吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          changeStatus({
            pointId: e.pointId,
            isValid: 0 // 1-启用，0-停用
          }).then(res => {
            console.log(res);
            if (res.code === 200) {
              self.msgSuccess(res.msg);
              self.getList();
            } else {
              self.msgError(res.msg);
            }
          }).catch(function() {
            if (loading != undefined) {
              loading.close();
            }
          });
        });
      },
      handleEnsable(e) {
        var self = this;
        this.$confirm("确定启用点位吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          changeStatus({
            pointId: e.pointId,
            isValid: 1 // 1-启用，0-停用
          }).then(res => {
            console.log(res);
            if (res.code === 200) {
              self.msgSuccess(res.msg);
              self.getList();
            } else {
              self.msgError(res.msg);
            }
          }).catch((error) => {
            console.log(error);
          });
        });
      },
      handleEdit(e) {
        var self = this;
        this.$refs.add.handleClick({
          info: e,
          title: "编辑点位",
          submit: info =>
            new Promise(resolve => {
              updatePoint(info).then(res => {
                if (res.code === 200) {
                  resolve(true); //操作成功 返回
                  self.msgSuccess(res.msg);
                } else {
                  resolve(false); //操作成功 返回
                  self.msgError(res.msg);
                }
              }).catch((error) => {
                console.log(error);
              });
            })
        });
      },
      handleDel(e) {
        var self = this;
        this.$confirm("确定删除点位吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          delPoint({
            pointIds: e.pointId,
          }).then(res => {
            if (res.code === 200) {
              self.msgSuccess(res.msg);
              self.getList();
            } else {
              self.msgError(res.msg);
            }
          }).catch((error) => {
            console.log(error);
          });
        });
      },
      handleAdd() {
        let self = this;
        this.$refs.add.handleClick({
          title: "添加点位",
          submit: info =>
            new Promise(resolve => {
              addPoint(info).then(res => {
                console.log(res, 22);
                if (res.code === 200) {
                  resolve(true); //操作成功 返回
                  self.msgSuccess("点位添加成功");
                } else {
                  resolve(false); //操作失败 返回
                  self.msgError(res.msg);
                }
              }).catch((error) => {
                console.log(error);
              });
            })
        });
      },
      zoomIn() {
        if (this.isZooming) return;
        this.isZooming = true;
        this.$refs.map.zoomIn().then(res => (this.isZooming = false));
      },
      zoomOut() {
        if (this.isZooming) return;
        this.isZooming = true;
        this.$refs.map.zoomOut().then(res => (this.isZooming = false));
      },
      handleMapChange(e) {
        let {
          center,
          zoom
        } = e.frameState.viewState;
        this.center = center;
        this.zoom = zoom;
      },
      // 获取点位数据
      getList(params) {
        this.loading = true;
        listPoint(params)
          .then(response => {
            this.pointList = response.rows;
          })
          .finally(res => (this.loading = false));
      },
      modify() {
        this.drawer = new Modify({
          features: new Collection(this.features),
          style: this.createStyle(),
          wrapX: this.wrapX
        });
        this.drawer.on('modifystart', this.handleModifyStart);
        this.drawer.on('modifyend', this.handleModify);
        this.map.addInteraction(this.drawer)
      },
      dragUpHandle(feature, event) {
        if (feature.getProperties().id === 'circleGreen') {
          this[feature.getProperties().id].point = event.coordinate
        }
      },
      overLayMouseMove(event) {
        if (this.dragOverlay) {
          for (var i = 0; i < this.pointList.length; i++) {
            var obj = this.pointList[i];
            if (obj.pointId == this.dragPointId) {
              obj.lon = event.coordinate[0];
              obj.lat = event.coordinate[1];
              obj.poposition = event.coordinate
            }
          }
          for (var obj in this.pointList) {
            if (obj.pointId == this.dragPointId) {
              obj.lon = event.coordinate[0];
              obj.lat = event.coordinate[1];
            }
          }
        }
        this.lonlat = event.coordinate;
      },
      overLayMouseDown(htmlVm, overlay, event) {
        this.dragOverlay = overlay;
        if (!this.dragBeforePoint) {
          this.dragBeforePoint = overlay.values_.position;
        }
        this.dragPointId = htmlVm.parentNode.firstChild.firstChild == null ? event.path[1].id.split("_")[1] : htmlVm.parentNode
          .firstChild.firstChild.id.split("_")[1];
      },
      overLayMouseUp(item) {
        this.handleEdit(item);
        this.dragOverlay = null
      }
    },
    created() {
      this.getList();
    }
  };
</script>

<style lang="scss" scoped>
  @media screen and (min--moz-device-pixel-ratio:0) {
    .ol-overlaycontainer {
      z-index: 1 !important;
    }
  }

  .xdh-map-html {
    cursor: move;
  }

  .point {
    background-color: rgb(240, 242, 245);
    position: relative;
    height: 100%;
  }

  .marker_point {
    text-align: center;
  }

  .markers-label-1 {
    background: #3492fc;
  }

  .marker_point {
    font-size: 14px;
    padding: 4px 7px;
    color: #fff;
  }

  @media (max-width: 1024px) {
    .chart-wrapper {
      padding: 8px;
    }
  }

  .xdh-map-placement is- left-bottom {
    margin: 15px;
  }

  .marker {
    cursor: pointer;
    text-align: center;

    // img {
    // 	width: 26px;
    // 	height: 31px;
    // }
    div {
      font-size: 12px;
      padding: 2px 5px;
      background-color: #fff;
    }
  }

  /deep/.xdh-map-popup {
    z-index: 1;
  }

  .zoom {
    user-select: none;
    position: absolute;
    z-index: 99;
    border-radius: 4px;
    border: 1px solid #ccc;
    background-color: #fff;
    overflow: hidden;
    color: #666;
    font-size: 32px;
    line-height: 30px;
    right: 24px;
    bottom: 24px;
    text-align: center;

    >div {
      width: 30px;
      height: 30px;
      cursor: pointer;
    }

    &:before {
      content: "";
      display: block;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
      height: 1px;
      width: 22px;
      background-color: #ccc;
    }
  }
</style>
